<?php

namespace App\Model;

use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Exception\Exception;

/**
 * Class UserMoneyLogModel
 * Create With Automatic Generator
 * @property $id
 * @property $user_id
 * @property $money_before
 * @property $money_change
 * @property $money_after
 * @property $type
 * @property $order_id
 * @property $info
 */
class UserMoneyLogModel extends AbstractModel
{
    protected $tableName = 'bee_user_money_log001';

    protected $primaryKey = 'id';

    protected $autoTimeStamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = false;

    /**
     * 设置分表名
     * @param int $userId
     * @return UserMoneyLogModel|string
     * @throws Exception
     */
    public function changeTableName(int $userId = 1)
    {
        $mod = $userId % 100;
        $trueTableName = 'bee_user_money_log' . str_pad($mod, 3, "0", STR_PAD_LEFT);
        return $this->tableName($trueTableName);
    }

    /**
     * 添加用户流水账记录
     * @param int $userId
     * @param float $originalMoney
     * @param float $changeMoney
     * @param int $type
     * @param int $orderId
     * @param string $info
     * @return bool|int
     * @throws Exception
     * @throws \Throwable
     */
    public function add(int $userId, float $originalMoney = 0.00, float $changeMoney = 0.00, int $type = 4, int $orderId = 0, string $info = '')
    {
        return $this->changeTableName($userId)->data([
            'user_id' => $userId,
            'money_before' => floatval($originalMoney),
            'money_change' => floatval($changeMoney),
            'money_after' => floatval($originalMoney) + floatval($changeMoney),
            'type' => $type,
            'order_id' => $orderId,
            'info' => $info,
        ], false)->save();
    }
}